﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using KeaoMDS.InfoManage;
using KeaoBase;
using System.Reflection;
using System.Threading;
using GoldPrinter;
using ThoughtWorks.QRCode.Codec;
using System.IO;
using KeaoMDS.AppCode;
using System.Net.Sockets;
using System.Net;

namespace KeaoMDS.Weight
{

    public enum WeightStatus
    {
        开始=0,
        结束=1
    }

    public partial class ChengZhong : BaseForm
    {
        private string m_ChengZhongLeiXing = string.Empty;//称重类型
        private decimal m_PianChaZhongLiang = 0m;//偏差重量
        private decimal m_MaoZhong = 0m;
        private decimal m_PiZhong = 0m;
        private decimal m_JingZhong = 0m;
        private decimal m_KouZhong = 0m;
        private decimal m_PianChaHouZhongLiang = 0m;//偏差后的重量
        private decimal m_DangQianZhongLiang = 0m;//当前重量
        private decimal m_ZiDongChePiZhongLiang = 0m;//自动车皮重量
        private string m_DangQianWuLiaoMingCheng = string.Empty;//当前选定的物料名称
        private string m_SheZhiQuXiang = "禁用";//设置物资去向
        private string m_JiSuanFangLiang = string.Empty;//计算方量
        private IntPtr m_Pic1 = IntPtr.Zero;
        private IntPtr m_Pic2 = IntPtr.Zero;
        private IntPtr m_Pic0 = IntPtr.Zero;
        private string m_SheZhiFaHuoZhongLiang = "禁用";//设置发货重量
        private SheZhiQuXiang m_BiaoDuan = null;
        private CheLiangPaiHao m_CheLiangPaiHao = null;
        private SheZhiFaHuoZhongLiang m_FaHuo = null;
        private int m_YiBiaoDuShu = 0;//仪表当前读数
        private bool m_WenDing = false;//仪表稳定状态
        private bool m_ListenSignl = false;//遥控信号


        private BaseVideo m_Video = null;
        private DataRow m_CurrentRow = null;
        private DataRow m_CurrentCheLiangRow = null;
        private WeightStatus m_WeightStatus = WeightStatus.结束;
        private Socket m_Socket = null;
        private byte[] m_SocketReadBytes = new byte[1024];

        public ChengZhong()
        {
            InitializeComponent();
            m_BiaoDuan = new SheZhiQuXiang();
            m_CheLiangPaiHao = new CheLiangPaiHao();
            m_FaHuo = new SheZhiFaHuoZhongLiang();
        }

        private void ChengZhong_Load(object sender, EventArgs e)
        {
            m_Pic1= pic_1.Handle;
            m_Pic2 = pic_2.Handle;
            m_Pic0 = pic_0.Handle;

            grid_ruku_weiwancheng.AutoGenerateColumns = false;
            grid_chuku_weiwancheng.AutoGenerateColumns = false;
            grid_ruku_yiwancheng.AutoGenerateColumns = false;
            grid_chuku_yiwancheng.AutoGenerateColumns = false;

            this.MinimumSize = this.Size;

            BindWuLiao();
            BindRuKuWeiWanCheng();
            BindChuKuWeiWanCheng();
            BindRuKuYiWanCheng();
            BindChuKuYiWanCheng();
            BindYunShuGongSi();

            try
            {
                m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                m_Socket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888));
                m_Socket.BeginReceive(m_SocketReadBytes, 0, 1024, SocketFlags.None, OnReadSocketBytes, 0);

                //ThreadPool.QueueUserWorkItem(new WaitCallback(Init));//初始化设备
                Thread t = new Thread(new ParameterizedThreadStart(Init));
                t.Start();

                Tmr_UI.Enabled = true;
            }
            catch(SocketException)
            {
                KeaoUtils.ShowInfoMessage("仪表服务未连接，请检查重试。");
            }
        }

        private void OnReadSocketBytes(IAsyncResult Args)
        {
            try
            {
                m_Socket.EndReceive(Args);
                m_YiBiaoDuShu = BitConverter.ToInt32(m_SocketReadBytes, 0);
                if (m_SocketReadBytes[4] == 0x01)
                {
                    m_WenDing = false;
                }
                else
                {
                    m_WenDing = true;
                }

                while (true)
                {
                   m_Socket.Receive(m_SocketReadBytes,0,m_SocketReadBytes.Length, SocketFlags.None);
                   m_YiBiaoDuShu = BitConverter.ToInt32(m_SocketReadBytes, 0);
                   if (m_SocketReadBytes[4] == 0x01)
                   {
                       m_WenDing = false;
                   }
                   else
                   {
                       m_WenDing = true;
                   }
                }
            }
            catch (Exception)
            {
                return;
            }
        }

        #region 初始化设备

        private void Init(object Args)
        {
            try
            {
                if (KeaoUtils.ConfigGetNodeAttr("视频监控", "状态") == "启用")
                {
                    m_Video = Assembly.LoadFrom("KeaoVideo.dll").CreateInstance(string.Format("KeaoVideo.{0}", KeaoUtils.ConfigGetNodeAttr("视频监控", "类型"))) as BaseVideo;
                    if (m_Video.ConnectDevice(KeaoUtils.ConfigGetNodeAttr("视频监控", "地址"), KeaoUtils.ConfigGetNodeAttr("视频监控", "登录名"),KeaoUtils.Decrypt( KeaoUtils.ConfigGetNodeAttr("视频监控", "登录密码")), int.Parse(KeaoUtils.ConfigGetNodeAttr("视频监控", "端口号"))))
                    {
                        if (KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号1") != "禁用")
                        {
                            ChannelHandle channelHandle = new ChannelHandle() { Channel = int.Parse(KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号1")), Handle = m_Pic1 };
                            m_Video.RealPlayByChannel(channelHandle);
                        }
                        if (KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号2") != "禁用")
                        {
                            ChannelHandle channelHandle = new ChannelHandle() { Channel = int.Parse(KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号2")), Handle = m_Pic2 };
                            m_Video.RealPlayByChannel(channelHandle);
                        }
                        if (KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号3") != "禁用")
                        {
                            ChannelHandle channelHandle = new ChannelHandle() { Channel = int.Parse(KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号3")), Handle = m_Pic0 };
                            m_Video.RealPlayByChannel(channelHandle);
                        }
                    }
                }
                if (MainForm.m_Listener != null && MainForm.m_Listener._Status == Status.正常)
                {
                    MainForm.m_Listener.OnListenSignal+=new ListenerEventHandle(m_Listener_OnListenSignal);
                }

            }
            catch (Exception err)
            {
                KeaoUtils.LogTxt(string.Format("初始化设备异常。{0}", err.Message));
            }
        }

        void m_Listener_OnListenSignal(object Sender, ListenArgs e)
        {
            try
            {
                //接收到遥控信号
                if (m_DangQianZhongLiang > 0m)
                {
                    TableRow newRow = new TableRow("tbl_yaokongjiance", Guid.NewGuid().ToString(), DBCtl.插入);
                    newRow.DataCols.Add(new TableCol() { ColName = "jianceshijian", ValueMember = DateTime.Now, ValueType = DataValueCommonType.日期时间 });
                    newRow.DataCols.Add(new TableCol() { ColName = "jianceshuju", ValueMember = e.ReadStr, ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "shujufujian", ValueMember = "未复检", ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "yingxiangzhongliang", ValueMember = "0", ValueType = DataValueCommonType.数字 });
                    newRow.DataCols.Add(new TableCol() { ColName = "shangchuanzhuangtai", ValueMember = "0", ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "zhandian", ValueMember = KeaoUtils.ConfigGetNodeAttr("客户", "站点"), ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "kehubianhao", ValueMember = KeaoUtils.ConfigGetNodeAttr("客户", "客户编号"), ValueType = DataValueCommonType.字符串 });
                    KeaoUtils._DB.SaveTableRows(newRow);
                    m_ListenSignl = true;//接收到遥控信号
                }
            }
            catch (Exception err)
            {
                KeaoUtils.LogTxt(string.Format("处理遥控信号数据异常。{0}", err.Message));
            }
        }
        #endregion

        #region 视频监控画面

        private void pic_1_DoubleClick(object sender, EventArgs e)
        {
            PictureBox currentPic = sender as PictureBox;
            if (currentPic.Parent is TableLayoutPanel)
            {
                tableLayoutPanel1.Visible = false;
                pic_0.Visible = false;
                currentPic.Parent = groupBox1;
               
            }
            else
            {
                tableLayoutPanel1.Visible = true;
                pic_0.Visible = true;
                currentPic.Parent = tableLayoutPanel1;
            }
        }

        #endregion

        #region 物料

        private void BindWuLiao()
        {
            try
            {
                Dictionary<string, string> orderDic = new Dictionary<string, string>();
                orderDic.Add("wuliaoleixing", "asc");
                string createCondition = KeaoUtils._DB.CreateAndCondition("wuliaozhuangtai", DataValueCommonType.字符串, "启用", "", SearchConditionType.等于);
                DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_wuliao", createCondition, orderDic);
                foreach (DataRow row in Dt.Rows)
                {
                    row["shangchuanzhuangtai"] = string.Format("{0}   |   {1}", row["wuliaoleixing"], row["wuliaomingcheng"]);
                }
                DataRow newRow = Dt.NewRow();
                newRow["id"] = "";
                newRow["shangchuanzhuangtai"] = "—请选择—";
                Dt.Rows.InsertAt(newRow, 0);
                cmb_wuliao.DisplayMember = "shangchuanzhuangtai";
                cmb_wuliao.ValueMember = "id";
                cmb_wuliao.DataSource = Dt;
            }
            catch (Exception err)
            {
                KeaoUtils.LogTxt(string.Format("绑定物料信息异常。{0}", err.Message));
            }
            
        }

        private void cmb_wuliao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cmb_wuliao.SelectedIndex != 0)
                {
                    //m_PianChaZhongLiang = 0m;//切换物料后首先把偏差重量设置为0
                    m_WeightStatus = WeightStatus.开始;
                }
                else
                {
                    m_WeightStatus = WeightStatus.结束;
                    cmb_xinghao.DataSource = null;
                    cmb_danweimingcheng.DataSource = null;
                    txt_chepaihao.DataSource = null;
                    return;
                }
                DataTable wuLiaoDt = cmb_wuliao.DataSource as DataTable;
                DataRow[] selectRows = wuLiaoDt.Select(string.Format("id='{0}'", cmb_wuliao.SelectedValue));
                m_ChengZhongLeiXing = string.Format("{0}", selectRows[0]["wuliaoleixing"]);
                m_DangQianWuLiaoMingCheng = string.Format("{0}", selectRows[0]["wuliaomingcheng"]);
                m_SheZhiQuXiang = string.Format("{0}", selectRows[0]["shezhiquxiang"]);
                m_SheZhiFaHuoZhongLiang = string.Format("{0}", selectRows[0]["shezhifahuozhongliang"]);
                lb_kouzhongfangshi.Text = string.Empty;
                txt_kouzhong.Text = string.Empty;
                m_JiSuanFangLiang = string.Empty;

                BindXingHao();
                BindCheLiang();
                BindDanWei();
            }
            catch (Exception err)
            {
                KeaoUtils.LogTxt(string.Format("选定物料异常。{0}", err.Message));
            }
        }

        private void BindXingHao()
        {
            try
            {
                string createCondition = KeaoUtils._DB.CreateAndCondition("wuliaobianhao", DataValueCommonType.字符串, string.Format("{0}", cmb_wuliao.SelectedValue), "", SearchConditionType.等于);
                DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_xinghao", createCondition);
                cmb_xinghao.DisplayMember = "xinghao";
                cmb_xinghao.ValueMember = "id";
                cmb_xinghao.DataSource = Dt;
            }
            catch (Exception err)
            {
                KeaoUtils.LogTxt(string.Format("绑定型号信息异常。{0}", err.Message));
            }
        }

        private void cmb_xinghao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cmb_xinghao.SelectedValue == null)
                {
                    return;
                }
                //选定型号
                DataTable Dt = cmb_xinghao.DataSource as DataTable;
                DataRow[] selectRows = Dt.Select(string.Format("id='{0}'", cmb_xinghao.SelectedValue));
                if (selectRows[0]["pianchazhuangtai"].Equals("启用"))
                {
                    if (!m_WenDing && m_DangQianZhongLiang <= 30m)
                    {
                        m_PianChaZhongLiang = Convert.ToDecimal(selectRows[0]["pianchazhongliang"]);
                    }
                    if (m_DangQianZhongLiang == 0m)
                    {
                        m_PianChaZhongLiang = Convert.ToDecimal(selectRows[0]["pianchazhongliang"]);
                    }
                }
                else
                {
                    if (!m_WenDing && m_DangQianZhongLiang <= 30m)
                    {
                        m_PianChaZhongLiang = 0m;
                    }
                    if (m_DangQianZhongLiang == 0m)
                    {
                        m_PianChaZhongLiang = 0m;
                    }
                }
                m_JiSuanFangLiang = string.Format("{0}", selectRows[0]["huansuangongshi"]);
                txt_kouzhong.Text = string.Format("{0}", selectRows[0]["morenkouzhong"]);
                lb_kouzhongfangshi.Text = string.Format("{0}", selectRows[0]["kouzhongfangshi"]);
                
            }
            catch (Exception err)
            {
                KeaoUtils.LogTxt(string.Format("选定型号异常。{0}", err.Message));
            }
        }


        #endregion

        #region 单位信息

        private void BindDanWei()
        {
             if (m_ChengZhongLeiXing == "入库物料")
            {
                string createCondition = KeaoUtils._DB.CreateAndCondition("danweileixing", DataValueCommonType.字符串, "入库单位", "", SearchConditionType.等于);
                createCondition += KeaoUtils._DB.CreateAndCondition("danweizhuangtai", DataValueCommonType.字符串, "启用", "", SearchConditionType.等于);
                DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_danwei", createCondition);
                cmb_danweimingcheng.DisplayMember = "danweimingcheng";
                cmb_danweimingcheng.ValueMember = "id";
                cmb_danweimingcheng.DataSource = Dt;
            }
            else
            {
                string createCondition = KeaoUtils._DB.CreateAndCondition("danweileixing", DataValueCommonType.字符串, "出库单位", "", SearchConditionType.等于);
                createCondition += KeaoUtils._DB.CreateAndCondition("danweizhuangtai", DataValueCommonType.字符串, "启用", "", SearchConditionType.等于);
                DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_danwei", createCondition);
                cmb_danweimingcheng.DisplayMember = "danweimingcheng";
                cmb_danweimingcheng.ValueMember = "id";
                cmb_danweimingcheng.DataSource = Dt;
            }
        }


        #endregion

        #region 车辆

        private void btn_chepaihao_Click(object sender, EventArgs e)
        {
            if (m_CheLiangPaiHao.ShowDialog() == DialogResult.OK)
            {
                txt_chepaihao.Text = m_CheLiangPaiHao.m_Current;
            }
        }

        private void BindCheLiang()
        {
            txt_chepaihao.Items.Clear();
            if (m_ChengZhongLeiXing == "入库物料")
            {
                string createCondition = KeaoUtils._DB.CreateAndCondition("cheliangleixing", DataValueCommonType.字符串, "入库车辆", "", SearchConditionType.等于);
                createCondition += KeaoUtils._DB.CreateAndCondition("cheliangzhuangtai", DataValueCommonType.字符串, "启用", "", SearchConditionType.等于);
                Dictionary<string, string> orderBys = new Dictionary<string, string>();
                orderBys.Add("chepaihao", "asc");
                DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_cheliang", createCondition,orderBys);
                //DataRow newRow = Dt.NewRow();
                //newRow["chepaihao"] = "—选择登记车辆—";
                //newRow["id"] = "";
                //Dt.Rows.InsertAt(newRow, 0);
                //txt_chepaihao.DisplayMember = "chepaihao";
                //txt_chepaihao.ValueMember = "id";
                //txt_chepaihao.DataSource = Dt;
                foreach (DataRow row in Dt.Rows)
                {
                    txt_chepaihao.Items.Add(string.Format("{0}",row["chepaihao"]));
                }

            }
            else
            {
                string createCondition = KeaoUtils._DB.CreateAndCondition("cheliangleixing", DataValueCommonType.字符串, "出库车辆", "", SearchConditionType.等于);
                createCondition += KeaoUtils._DB.CreateAndCondition("cheliangzhuangtai", DataValueCommonType.字符串, "启用", "", SearchConditionType.等于);
                Dictionary<string, string> orderBys = new Dictionary<string, string>();
                orderBys.Add("chepaihao", "asc");
                DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_cheliang", createCondition,orderBys);
                //DataRow newRow = Dt.NewRow();
                //newRow["chepaihao"] = "—选择登记车辆—";
                //newRow["id"] = "";
                //Dt.Rows.InsertAt(newRow, 0);
                //txt_chepaihao.DisplayMember = "chepaihao";
                //txt_chepaihao.ValueMember = "id";
                //txt_chepaihao.DataSource = Dt;
                foreach (DataRow row in Dt.Rows)
                {
                    txt_chepaihao.Items.Add(string.Format("{0}", row["chepaihao"]));
                }
            }
        }

        #endregion

        #region 未完成信息

        private void grid_ruku_weiwancheng_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1);
        }

        private void grid_chuku_weiwancheng_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1);
        }

        private void BindRuKuWeiWanCheng()
        {
            Dictionary<string, string> orderCondition = new Dictionary<string, string>();
            orderCondition.Add("chengzhongshijian", "desc");
            string createCondition = KeaoUtils._DB.CreateAndCondition("chengzhongleixing", DataValueCommonType.字符串, "入库物料", "", SearchConditionType.等于);
            DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_chengzhonglinshi", createCondition,orderCondition);
            grid_ruku_weiwancheng.DataSource = Dt;
        }

        private void BindChuKuWeiWanCheng()
        {
            Dictionary<string, string> orderCondition = new Dictionary<string, string>();
            orderCondition.Add("chengzhongshijian", "desc");
            string createCondition = KeaoUtils._DB.CreateAndCondition("chengzhongleixing", DataValueCommonType.字符串, "出库物料", "", SearchConditionType.等于);
            DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_chengzhonglinshi", createCondition,orderCondition);
            grid_chuku_weiwancheng.DataSource = Dt;
        }

        private void contextMenu_1_xiugai_Click(object sender, EventArgs e)
        {
            if (!string.Format("{0}", KeaoUtils._CurrentUserRow["juesequanxian"]).Contains("未完成信息修改"))
            {
                KeaoUtils.ShowInfoMessage("该用户没有操作权限。");
                return;
            }

            //修改未完成
            if (tabControl1.SelectedIndex == 0)
            {
                if (grid_ruku_weiwancheng.SelectedRows.Count==0)
                {
                    return;
                }
                int selectIndex = grid_ruku_weiwancheng.SelectedRows[0].Index;
                WeiWanChengXiuGai xiuGai = new WeiWanChengXiuGai(grid_ruku_weiwancheng.SelectedRows[0], "入库物料");
                if (xiuGai.ShowDialog() == DialogResult.OK)
                {
                    BindRuKuWeiWanCheng();
                    grid_ruku_weiwancheng.Rows[selectIndex].Selected = true;
                }
            }
            else
            {
                if (grid_chuku_weiwancheng.SelectedRows.Count==0)
                {
                    return;
                }
                int selectIndx = grid_chuku_weiwancheng.SelectedRows[0].Index;
                WeiWanChengXiuGai xiuGai = new WeiWanChengXiuGai(grid_chuku_weiwancheng.SelectedRows[0], "出库物料");
                if (xiuGai.ShowDialog() == DialogResult.OK)
                {
                    BindChuKuWeiWanCheng();
                    grid_chuku_weiwancheng.Rows[selectIndx].Selected = true;
                }
            }
        }

        private void contextMenu_1_shanchu_Click(object sender, EventArgs e)
        {
            //删除未完成
            if (!string.Format("{0}", KeaoUtils._CurrentUserRow["juesequanxian"]).Contains("未完成信息修改"))
            {
                KeaoUtils.ShowInfoMessage("该用户没有操作权限。");
                return;
            }
            if (tabControl1.SelectedIndex == 0)
            {
                if (grid_ruku_weiwancheng.SelectedRows.Count ==0)
                {
                    return;
                }
                if (KeaoUtils.ShowQuestionMessage("确定要删除该入库信息吗？") == DialogResult.Yes)
                {
                    if (KeaoUtils._DB.DeleteRowByID(new TableRow() { ID = string.Format("{0}", grid_ruku_weiwancheng.SelectedRows[0].Cells["weiwancheng_ruku_id"].Value), TableName = "tbl_chengzhonglinshi" }) > 0)
                    {
                        KeaoUtils.ShowInfoMessage("已删除。");
                        BindRuKuWeiWanCheng();
                    }
                }
            }
            else
            {
                if (grid_chuku_weiwancheng.SelectedRows.Count==0)
                {
                    return;
                }
                if (KeaoUtils.ShowQuestionMessage("确定要删除该出库信息吗？") == DialogResult.Yes)
                {
                    if (KeaoUtils._DB.DeleteRowByID(new TableRow() { ID = string.Format("{0}", grid_chuku_weiwancheng.SelectedRows[0].Cells["weiwancheng_chuku_id"].Value), TableName = "tbl_chengzhonglinshi" }) > 0)
                    {
                        KeaoUtils.ShowInfoMessage("已删除。");
                        BindChuKuWeiWanCheng();
                    }
                }
            }
        }

        private void grid_ruku_weiwancheng_DoubleClick(object sender, EventArgs e)
        {
            //选定未完成入库记录
            if (grid_ruku_weiwancheng.SelectedRows.Count==0)
            {
                return;
            }
            txt_chepaihao.Text = string.Format("{0}", grid_ruku_weiwancheng.SelectedRows[0].Cells["weiwancheng_ruku_chepaihao"].Value);
        }

        private void grid_chuku_weiwancheng_DoubleClick(object sender, EventArgs e)
        {
            //选定未完成出库记录
            if (grid_chuku_weiwancheng.SelectedRows.Count==0)
            {
                return;
            }
            txt_chepaihao.Text = string.Format("{0}", grid_chuku_weiwancheng.SelectedRows[0].Cells["weiwancheng_chuku_chepaihao"].Value);
        }

        #endregion

        #region 已完成信息

        private void grid_ruku_yiwancheng_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1);
        }

        private void grid_chuku_yiwancheng_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1);
        }

        private void BindRuKuYiWanCheng()
        {
            try
            {
                Dictionary<string, string> orderCondition = new Dictionary<string, string>();
                orderCondition.Add("pizhongshijian", "desc");
                DateTime kaiShi = DateTime.Parse(string.Format("{0} 00:00:00", DateTime.Today.ToString("yyyy-MM-dd")));
                string createCondition = KeaoUtils._DB.CreateAndCondition("pizhongshijian", DataValueCommonType.日期时间, kaiShi.ToString("yyyy-MM-dd HH:mm:ss"), kaiShi.AddHours(23).AddMinutes(59).AddSeconds(59).ToString("yyyy-MM-dd HH:mm:ss"), SearchConditionType.between);
                createCondition += KeaoUtils._DB.CreateAndCondition("chengzhongleixing", DataValueCommonType.字符串, "入库物料", "", SearchConditionType.等于);
                DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_chengzhong", createCondition, orderCondition);
                if (Dt.Rows.Count > 0)
                {
                    DataTable DtCount = KeaoUtils._DB.GetDataTableByCondition("tbl_chengzhong", "count(id) as cheshu,sum(maozhong) as maozhong,sum(pizhong) as pizhong,sum(kouzhong) as kouzhong ,sum(jingzhong) as jingzhong", null, createCondition, null, null);
                    DataRow newRow = Dt.NewRow();
                    newRow["chengzhongbianhao"] = "合计：";
                    newRow["chepaihao"] = string.Format("{0}车", DtCount.Rows[0]["cheshu"]);
                    newRow["jingzhong"] = DtCount.Rows[0]["jingzhong"];
                    Dt.Rows.Add(newRow);
                }
                grid_ruku_yiwancheng.DataSource = Dt;
                grid_ruku_yiwancheng.AutoResizeColumns();
            }
            catch (Exception err)
            {
                KeaoUtils.LogTxt(string.Format("绑定入库已完成信息异常。{0}", err.Message));
            }

        }

        private void BindChuKuYiWanCheng()
        {
            try
            {
                Dictionary<string, string> orderCondition = new Dictionary<string, string>();
                orderCondition.Add("maozhongshijian", "desc");
                DateTime kaiShi = DateTime.Parse(string.Format("{0} 00:00:00", DateTime.Today.ToString("yyyy-MM-dd")));
                string createCondition = KeaoUtils._DB.CreateAndCondition("maozhongshijian", DataValueCommonType.日期时间, kaiShi.ToString("yyyy-MM-dd HH:mm:ss"), kaiShi.AddHours(23).AddMinutes(59).AddSeconds(59).ToString("yyyy-MM-dd HH:mm:ss"), SearchConditionType.between);
                createCondition += KeaoUtils._DB.CreateAndCondition("chengzhongleixing", DataValueCommonType.字符串, "出库物料", "", SearchConditionType.等于);
                DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_chengzhong", createCondition, orderCondition);
                if (Dt.Rows.Count > 0)
                {
                    DataTable DtCount = KeaoUtils._DB.GetDataTableByCondition("tbl_chengzhong", "count(id) as cheshu,sum(maozhong) as maozhong,sum(pizhong) as pizhong,sum(kouzhong) as kouzhong,sum(jingzhong) as jingzhong", null, createCondition, null, null);
                    DataRow newRow = Dt.NewRow();
                    newRow["chengzhongbianhao"] = "合计：";
                    newRow["chepaihao"] = string.Format("{0}车", DtCount.Rows[0]["cheshu"]);
                    newRow["jingzhong"] = DtCount.Rows[0]["jingzhong"];
                    Dt.Rows.Add(newRow);
                }
                grid_chuku_yiwancheng.DataSource = Dt;
                grid_chuku_yiwancheng.AutoResizeColumns();
            }
            catch (Exception err)
            {

                KeaoUtils.LogTxt(string.Format("绑定出库已完成信息异常。{0}", err.Message));
            }
        }

        private void contextMenu_2_xiugai_Click(object sender, EventArgs e)
        {
            //修改已完成
            if (!string.Format("{0}", KeaoUtils._CurrentUserRow["juesequanxian"]).Contains("已完成信息修改"))
            {
                KeaoUtils.ShowInfoMessage("该用户没有操作权限。");
                return;
            }

            if (tabControl1.SelectedIndex == 2)
            {
                if (grid_ruku_yiwancheng.SelectedRows .Count==0)
                {
                    return;
                }
                if (grid_ruku_yiwancheng.SelectedRows[0].Cells["yiwancheng_ruku_id"].Value == DBNull.Value)
                {
                    return;
                }
                int selectIndex = grid_ruku_yiwancheng.SelectedRows[0].Index;
                YiWanChengXiuGai yiWanChengXiuGai = new YiWanChengXiuGai(string.Format("{0}",grid_ruku_yiwancheng.SelectedRows[0].Cells["yiwancheng_ruku_id"].Value),"入库物料");
                if (yiWanChengXiuGai.ShowDialog() == DialogResult.OK)
                {
                    BindRuKuYiWanCheng();
                    grid_ruku_yiwancheng.Rows[selectIndex].Selected = true;
                    if (OnChengZhong != null)
                    {
                        OnChengZhong(null, null);
                    }
                }
            }
            else
            {
                if (grid_chuku_yiwancheng.SelectedRows.Count==0)
                {
                    return;
                }
                if (grid_chuku_yiwancheng.SelectedRows[0].Cells["yiwancheng_chuku_id"].Value == DBNull.Value)
                {
                    return;
                }
                int selectIndex = grid_chuku_yiwancheng.SelectedRows[0].Index;
                YiWanChengXiuGai yiWanChengXiuGai = new YiWanChengXiuGai(string.Format("{0}",grid_chuku_yiwancheng.SelectedRows[0].Cells["yiwancheng_chuku_id"].Value), "出库物料");
                if (yiWanChengXiuGai.ShowDialog() == DialogResult.OK)
                {
                    BindChuKuYiWanCheng();
                    grid_chuku_yiwancheng.Rows[selectIndex].Selected = true;
                    if (OnChengZhong != null)
                    {
                        OnChengZhong(null, null);
                    }
                }
            }
        }

        private void contextMenu_2_shanchu_Click(object sender, EventArgs e)
        {
            if (!string.Format("{0}", KeaoUtils._CurrentUserRow["juesequanxian"]).Contains("已完成信息修改"))
            {
                KeaoUtils.ShowInfoMessage("该用户没有操作权限。");
                return;
            }

            if (tabControl1.SelectedIndex == 2)
            {
                if (grid_ruku_yiwancheng.SelectedRows.Count==0)
                {
                    return;
                }
                if (grid_ruku_yiwancheng.SelectedRows[0].Cells["yiwancheng_ruku_chengzhongbianhao"].Value == DBNull.Value)
                {
                    return;
                }
                if (KeaoUtils.ShowQuestionMessage("确定要删除该入库信息吗？") == DialogResult.Yes)
                {
                    MainForm.RiZhi(string.Format("删除入库已完成信息，单号【{0}】", grid_ruku_yiwancheng.SelectedRows[0].Cells["yiwancheng_ruku_chengzhongbianhao"].Value));
                    if (KeaoUtils._DB.DeleteRowByID(new TableRow() { TableName = "tbl_chengzhong", ID = string.Format("{0}", grid_ruku_yiwancheng.SelectedRows[0].Cells["yiwancheng_ruku_id"].Value) }) > 0)
                    {
                        KeaoUtils.ShowInfoMessage("已删除。");
                        BindRuKuYiWanCheng();
                        if (OnChengZhong != null)
                        {
                            OnChengZhong(null, null);
                        }
                    }
                }
            }
            else
            {
                if (grid_chuku_yiwancheng.SelectedRows.Count==0)
                {
                    return;
                }
                if (grid_chuku_yiwancheng.SelectedRows[0].Cells["yiwancheng_chuku_id"].Value == DBNull.Value)
                {
                    return;
                }
                if (KeaoUtils.ShowQuestionMessage("确定要删除该出库信息吗？") == DialogResult.Yes)
                {
                    if (KeaoUtils._DB.DeleteRowByID(new TableRow() { TableName = "tbl_chengzhong", ID = string.Format("{0}", grid_chuku_yiwancheng.SelectedRows[0].Cells["yiwancheng_chuku_id"].Value) }) > 0)
                    {
                        KeaoUtils.ShowInfoMessage("已删除。");
                        BindChuKuYiWanCheng();
                        if (OnChengZhong != null)
                        {
                            OnChengZhong(null, null);
                        }
                        MainForm.RiZhi(string.Format("删除出库已完成信息，单号【{0}】", grid_chuku_yiwancheng.SelectedRows[0].Cells["yiwancheng_chuku_chengzhongbianhao"].Value));
                    }
                }
            }
        }

        private void contextMenu_2_bangdan_Click(object sender, EventArgs e)
        {
            if (!string.Format("{0}", KeaoUtils._CurrentUserRow["juesequanxian"]).Contains("磅单补打"))
            {
                KeaoUtils.ShowInfoMessage("该用户没有操作权限。");
                return;
            }
            
            if (tabControl1.SelectedIndex == 2)
            {
                if (grid_ruku_yiwancheng.SelectedRows.Count==0)
                {
                    return;
                }
                if (grid_ruku_yiwancheng.SelectedRows[0].Cells["yiwancheng_ruku_id"].Value == DBNull.Value)
                {
                    return;
                }
                if (KeaoUtils.ShowQuestionMessage("原磅单将作废，确定要补打磅单吗？") == DialogResult.Yes)
                {
                    KeaoPrinter.Print(grid_ruku_yiwancheng.SelectedRows[0].Cells["yiwancheng_ruku_id"].Value,true);
                }
            }
            else
            {
                if (grid_chuku_yiwancheng.SelectedRows.Count==0)
                {
                    return;
                }
                if (grid_chuku_yiwancheng.SelectedRows[0].Cells["yiwancheng_chuku_id"].Value == DBNull.Value)
                {
                    return;
                }
                if (KeaoUtils.ShowQuestionMessage("原磅单将作废，确定要补打磅单吗？") == DialogResult.Yes)
                {
                    KeaoPrinter.Print(grid_chuku_yiwancheng.SelectedRows[0].Cells["yiwancheng_chuku_id"].Value,true);
                }
            }
        }

        #endregion

        #region 称重

        private void btn_chengzhong_Click(object sender, EventArgs e)
        {
            if (m_ListenSignl)
            {
                KeaoUtils.ShowWarnMessage("监测到疑似遥控作弊信号，请车辆下磅，仪表归零后重新上磅称重。");
                return;
            }
            if (m_DangQianZhongLiang == 0m)
            {
                KeaoUtils.ShowInfoMessage("重量不正确，暂时不能称重。");
                return;
            }
            if (!m_WenDing)
            {
                KeaoUtils.ShowInfoMessage("重量不稳定，暂时不能称重。");
                return;
            }
            if (cmb_wuliao.Text == "—请选择—")
            {
                KeaoUtils.ShowInfoMessage("请选择物料。");
                return;
            }
            if (string.IsNullOrEmpty(txt_chepaihao.Text) || txt_chepaihao.Text.Contains("登记车辆"))
            {
                KeaoUtils.ShowInfoMessage("车辆信息不正确，请检查后重试。");
                return;
            }
            if (string.IsNullOrEmpty(cmb_danweimingcheng.Text))
            {
                KeaoUtils.ShowInfoMessage("没有单位信息，暂时不能称重。");
                return;
            }
            if (!string.IsNullOrEmpty(txt_kouzhong.Text) && !KeaoUtils.isNumber(txt_kouzhong.Text))
            {
                KeaoUtils.ShowInfoMessage("请输入正确的扣重数据。");
                return;
            }

            try
            {

                if (m_CurrentRow == null)
                {
                    //一次称重
                    if (m_ZiDongChePiZhongLiang == 0m)
                    {
                        string tupian1 = string.Empty;
                        string tupian2 = string.Empty;
                        string tupian3 = string.Empty;
                        if (m_Video != null)
                        {
                            if (!KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号1").Equals("禁用"))
                            {
                                tupian1 = m_Video.CapturePicByChannel(int.Parse(KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号1")));
                            }
                            if (!KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号2").Equals("禁用"))
                            {
                                tupian2 = m_Video.CapturePicByChannel(int.Parse(KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号2")));
                            }
                            if (!KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号3").Equals("禁用"))
                            {
                                tupian3 = m_Video.CapturePicByChannel(int.Parse(KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号3")));
                            }
                        }

                        decimal faHuoZhongLiang = 0m;
                        if (m_SheZhiFaHuoZhongLiang == "启用")
                        {
                            m_FaHuo.ShowDialog();
                            faHuoZhongLiang = Convert.ToDecimal(m_FaHuo.m_FaHuoZhongLiang);
                        }

                        decimal moReKouZhong = 0m;
                        if (!string.IsNullOrEmpty(txt_kouzhong.Text))
                        {
                            moReKouZhong = Convert.ToDecimal(txt_kouzhong.Text);
                        }

                        TableRow newRow = new TableRow("tbl_chengzhonglinshi", KeaoUtils.GetGUID(), DBCtl.插入);
                        newRow.DataCols.Add(new TableCol() { ColName = "yicizhongliang", ValueMember = m_PianChaHouZhongLiang.ToString("0.00"), ValueType = DataValueCommonType.数字 });
                        newRow.DataCols.Add(new TableCol() { ColName = "wuliaomingcheng", ValueMember = m_DangQianWuLiaoMingCheng, ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "xinghao", ValueMember = cmb_xinghao.Text, ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "danweimingcheng", ValueMember = cmb_danweimingcheng.Text, ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "chepaihao", ValueMember = txt_chepaihao.Text, ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "chekahao", ValueMember = "", ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "chengzhongshijian", ValueMember = DateTime.Now, ValueType = DataValueCommonType.日期时间 });
                        newRow.DataCols.Add(new TableCol() { ColName = "chengzhongleixing", ValueMember = m_ChengZhongLeiXing, ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "chengzhongrenyuan", ValueMember = KeaoUtils._CurrentUserRow["yonghuxingming"], ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "tupian1", ValueMember = tupian1, ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "tupian2", ValueMember = tupian2, ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "tupian3", ValueMember = tupian3, ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "fahuozhongliang", ValueMember = faHuoZhongLiang.ToString("0.00"), ValueType = DataValueCommonType.数字 });
                        newRow.DataCols.Add(new TableCol() { ColName = "pianchazhongliang", ValueMember = m_PianChaZhongLiang.ToString("0.00"), ValueType = DataValueCommonType.数字 });
                        newRow.DataCols.Add(new TableCol() { ColName="shezhiquxiang", ValueMember=m_SheZhiQuXiang, ValueType= DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "huansuangongshi", ValueMember = m_JiSuanFangLiang, ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName="morenkouzhong", ValueMember=moReKouZhong.ToString("0.00"), ValueType= DataValueCommonType.数字 });
                        newRow.DataCols.Add(new TableCol() { ColName="kouzhongfangshi", ValueMember=string.IsNullOrEmpty(lb_kouzhongfangshi.Text)?"普通扣重":lb_kouzhongfangshi.Text, ValueType= DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "yunshugongsi", ValueMember = cmb_yunshugongsi.SelectedIndex == 0 ? "" : cmb_yunshugongsi.Text, ValueType = DataValueCommonType.字符串 });
                       
                        if (KeaoUtils._DB.SaveTableRows(newRow) > 0)
                        {
                            if (m_ChengZhongLeiXing == "入库物料")
                            {
                                tabControl1.SelectedIndex = 0;
                            }
                            else
                            {
                                tabControl1.SelectedIndex = 1;
                            }

                            btn_refresh_Click(null, null);

                            lb_yici.Text = newRow.DataCols[0].ValueMember.ToString();
                        }
                        else
                        {
                            KeaoUtils.ShowInfoMessage("保存信息失败，请重试。");
                            btn_refresh_Click(null, null);
                        }
                    }
                    else
                    {
                        //车皮重量自动称重模式
                        m_MaoZhong = m_PianChaHouZhongLiang;
                        m_PiZhong = m_ZiDongChePiZhongLiang;

                        if (!string.IsNullOrEmpty(txt_kouzhong.Text))
                        {
                            if (lb_kouzhongfangshi.Text == "普通扣重")
                            {
                                m_KouZhong = Convert.ToDecimal(txt_kouzhong.Text);
                            }
                            else
                            {
                                m_KouZhong = (m_MaoZhong - m_PiZhong) * Convert.ToDecimal(txt_kouzhong.Text) / 100;
                            }
                        }
                        m_JingZhong = m_MaoZhong - m_PiZhong - m_KouZhong;

                        if (m_JingZhong <= 0m)
                        {
                            KeaoUtils.ShowWarnMessage("净重不正确，请检查后重试...");
                            return;
                        }

                        if (m_SheZhiQuXiang == "启用")
                        {
                            if (m_BiaoDuan.ShowDialog() == DialogResult.OK)
                            {
                                m_SheZhiQuXiang = m_BiaoDuan.m_QuXiangBianHao;
                            }
                            else
                            {
                                m_SheZhiQuXiang = "";
                            }
                        }
                        else
                        {
                            m_SheZhiQuXiang = "";
                        }

                        decimal jiSuanFangLiang = 0m;
                        if (!string.IsNullOrEmpty(m_JiSuanFangLiang))
                        {
                            jiSuanFangLiang = KeaoUtils.Calculator(m_JiSuanFangLiang.Replace("T", m_JingZhong.ToString()));
                        }

                        decimal faHuoZhongLiang = 0m;
                        if (m_SheZhiFaHuoZhongLiang == "启用")
                        {
                            m_FaHuo.ShowDialog();
                            faHuoZhongLiang =Convert.ToDecimal(m_FaHuo.m_FaHuoZhongLiang);
                        }

                        string tupian1 = string.Empty;
                        string tupian2 = string.Empty;
                        string tupian3 = string.Empty;
                        if (m_Video != null)
                        {
                            if (!KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号1").Equals("禁用"))
                            {
                                tupian1 = m_Video.CapturePicByChannel(int.Parse(KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号1")));
                            }
                            if (!KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号2").Equals("禁用"))
                            {
                                tupian2 = m_Video.CapturePicByChannel(int.Parse(KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号2")));
                            }
                            if (!KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号3").Equals("禁用"))
                            {
                                tupian3 = m_Video.CapturePicByChannel(int.Parse(KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号3")));
                            }
                        }

                        string chengZhongBianHao = KeaoUtils.GetGUID();
                        TableRow newRow = new TableRow("tbl_chengzhong", chengZhongBianHao, DBCtl.插入);
                        newRow.DataCols.Add(new TableCol() { ColName = "maozhong", ValueMember = m_MaoZhong.ToString("0.00"), ValueType = DataValueCommonType.数字 });
                        newRow.DataCols.Add(new TableCol() { ColName = "pizhong", ValueMember = m_PiZhong.ToString("0.00"), ValueType = DataValueCommonType.数字 });
                        newRow.DataCols.Add(new TableCol() { ColName = "jingzhong", ValueMember = m_JingZhong.ToString("0.00"), ValueType = DataValueCommonType.数字 });
                        newRow.DataCols.Add(new TableCol() { ColName = "kouzhong", ValueMember = m_KouZhong.ToString("0.00"), ValueType = DataValueCommonType.数字 });
                        newRow.DataCols.Add(new TableCol() { ColName = "pianchazhongliang", ValueMember = m_PianChaZhongLiang.ToString("0.00"), ValueType = DataValueCommonType.数字 });
                        newRow.DataCols.Add(new TableCol() { ColName = "chepaihao", ValueMember = txt_chepaihao.Text, ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "wuliaomingcheng", ValueMember = m_DangQianWuLiaoMingCheng, ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "xinghao", ValueMember = cmb_xinghao.Text, ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "danweimingcheng", ValueMember = cmb_danweimingcheng.Text, ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "quxiangbiaoduan", ValueMember = m_SheZhiQuXiang, ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "chengzhongleixing", ValueMember = m_ChengZhongLeiXing, ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "chengzhongbianhao", ValueMember = "", ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "jisuanfangliang", ValueMember = jiSuanFangLiang.ToString("0.00"), ValueType = DataValueCommonType.数字 });
                        newRow.DataCols.Add(new TableCol() { ColName = "maozhongshijian", ValueMember = DateTime.Now, ValueType = DataValueCommonType.日期时间 });
                        newRow.DataCols.Add(new TableCol() { ColName = "pizhongshijian", ValueMember = DateTime.Now, ValueType = DataValueCommonType.日期时间 });
                        newRow.DataCols.Add(new TableCol() { ColName = "maozhongrenyuan", ValueMember = string.Format("{0}", KeaoUtils._CurrentUserRow["yonghuxingming"]), ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "pizhongrenyuan", ValueMember = string.Format("{0}", KeaoUtils._CurrentUserRow["yonghuxingming"]), ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "maozhongtupian1", ValueMember = tupian1, ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "maozhongtupian2", ValueMember = tupian2, ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "maozhongtupian3", ValueMember = tupian3, ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "pizhongtupian1", ValueMember = tupian1, ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "pizhongtupian2", ValueMember = tupian2, ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "pizhongtupian3", ValueMember = tupian3, ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "jiage", ValueMember = "0.00", ValueType = DataValueCommonType.数字 });
                        newRow.DataCols.Add(new TableCol() { ColName = "jin_e", ValueMember = "0.00", ValueType = DataValueCommonType.数字 });
                        newRow.DataCols.Add(new TableCol() { ColName = "shangchuanzhuangtai", ValueMember = "0", ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "beizhu", ValueMember ="" , ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "caozuojilu", ValueMember = "预设车辆皮重", ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "yunshugongsi", ValueMember = cmb_yunshugongsi.SelectedIndex == 0 ? "" : cmb_yunshugongsi.Text, ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName="fahuozhongliang", ValueMember=faHuoZhongLiang.ToString("0.00"), ValueType= DataValueCommonType.数字 });
                        newRow.DataCols.Add(new TableCol() { ColName = "zhandian", ValueMember = KeaoUtils.ConfigGetNodeAttr("客户", "站点"), ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "bangfang", ValueMember = KeaoUtils.ConfigGetNodeAttr("客户", "磅房"), ValueType = DataValueCommonType.字符串 });
                        newRow.DataCols.Add(new TableCol() { ColName = "kehubianhao", ValueMember = KeaoUtils.ConfigGetNodeAttr("客户", "客户编号"), ValueType = DataValueCommonType.字符串 });
                        if (KeaoUtils._DB.SaveTableRows(newRow) > 0)
                        {
                            TableRow updateBianHaoRow = new TableRow() { TableName = "tbl_chengzhong", ID = newRow.ID, Ctl = DBCtl.修改 };
                            updateBianHaoRow.DataCols.Add(new TableCol() { ColName = "chengzhongbianhao", ValueMember = KeaoUtils.GetSerialNumber(), ValueType = DataValueCommonType.字符串 });
                            KeaoUtils._DB.SaveTableRows(updateBianHaoRow);
                            
                            if (m_ChengZhongLeiXing == "入库物料")
                            {
                                tabControl1.SelectedIndex = 2;
                            }
                            else
                            {
                                tabControl1.SelectedIndex = 3;
                            }

                            btn_refresh_Click(null, null);//刷新数据
                            lb_yici.Text = newRow.DataCols[0].ValueMember.ToString();
                            lb_erci.Text = newRow.DataCols[1].ValueMember.ToString();
                            lb_kouzhong.Text = newRow.DataCols[3].ValueMember.ToString();
                            lb_jingzhong.Text = newRow.DataCols[2].ValueMember.ToString();

                            //ThreadPool.QueueUserWorkItem(new WaitCallback(KeaoPrinter.Print), newRow.ID);
                            //Thread t = new Thread(new ParameterizedThreadStart(KeaoPrinter.Print));
                            //t.Start(newRow.ID);
                            KeaoPrinter.Print(newRow.ID, false);

                            if (OnChengZhong != null)
                            {
                                OnChengZhong(null, null);
                            }
                        }
                        else
                        {
                            KeaoUtils.ShowInfoMessage("保存信息失败，请重试。");
                            btn_refresh_Click(null, null);
                        }
                    }

                }
                else
                {
                    //二次称重
                    if (m_ChengZhongLeiXing == "入库物料")
                    {
                        m_MaoZhong = Convert.ToDecimal(m_CurrentRow["yicizhongliang"]);
                        m_PiZhong = m_PianChaHouZhongLiang;
                    }
                    else
                    {
                        m_MaoZhong = m_PianChaHouZhongLiang;
                        m_PiZhong = Convert.ToDecimal(m_CurrentRow["yicizhongliang"]);
                    }

                    if (!string.IsNullOrEmpty(txt_kouzhong.Text))
                    {
                        if (lb_kouzhongfangshi.Text== "普通扣重")
                        {
                            m_KouZhong = Convert.ToDecimal(txt_kouzhong.Text);
                        }
                        else
                        {
                            m_KouZhong = (m_MaoZhong - m_PiZhong) * Convert.ToDecimal(txt_kouzhong.Text) / 100;
                        }
                    }
                    m_JingZhong = m_MaoZhong - m_PiZhong - m_KouZhong;

                    if (m_JingZhong <= 0m)
                    {
                        KeaoUtils.ShowWarnMessage("净重不正确，请检查后重试...");
                        return;
                    }

                    if (m_CurrentRow["shezhiquxiang"].Equals("启用"))
                    {
                        if (m_BiaoDuan.ShowDialog() == DialogResult.OK)
                        {
                            m_SheZhiQuXiang = m_BiaoDuan.m_QuXiangBianHao;
                        }
                        else
                        {
                            m_SheZhiQuXiang = "";
                        }
                    }
                    else
                    {
                        m_SheZhiQuXiang = "";
                    }

                    decimal jiSuanFangLiang = 0m;
                    if (!m_CurrentRow["huansuangongshi"].Equals(""))
                    {
                        jiSuanFangLiang = KeaoUtils.Calculator(string.Format("{0}", m_CurrentRow["huansuangongshi"]).Replace("T", m_JingZhong.ToString()));
                    }


                    string tupian1 = string.Empty;
                    string tupian2 = string.Empty;
                    string tupian3 = string.Empty;
                    if (m_Video != null)
                    {
                        if (!KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号1").Equals("禁用"))
                        {
                            tupian1 = m_Video.CapturePicByChannel(int.Parse(KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号1")));
                        }
                        if (!KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号2").Equals("禁用"))
                        {
                            tupian2 = m_Video.CapturePicByChannel(int.Parse(KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号2")));
                        }
                        if (!KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号3").Equals("禁用"))
                        {
                            tupian3 = m_Video.CapturePicByChannel(int.Parse(KeaoUtils.ConfigGetNodeAttr("视频监控", "通道号3")));
                        }
                    }

                    string chengZhongID = KeaoUtils.GetGUID();
                    DateTime d1 = Convert.ToDateTime(m_CurrentRow["chengzhongshijian"]);
                    DateTime d2 = DateTime.Now;
                    TableRow newRow = new TableRow("tbl_chengzhong", chengZhongID, DBCtl.插入);
                    newRow.DataCols.Add(new TableCol() { ColName = "maozhong", ValueMember = m_MaoZhong.ToString("0.00"), ValueType = DataValueCommonType.数字 });
                    newRow.DataCols.Add(new TableCol() { ColName = "pizhong", ValueMember = m_PiZhong.ToString("0.00"), ValueType = DataValueCommonType.数字 });
                    newRow.DataCols.Add(new TableCol() { ColName = "jingzhong", ValueMember = m_JingZhong.ToString("0.00"), ValueType = DataValueCommonType.数字 });
                    newRow.DataCols.Add(new TableCol() { ColName = "kouzhong", ValueMember = m_KouZhong.ToString("0.00"), ValueType = DataValueCommonType.数字 });
                    newRow.DataCols.Add(new TableCol() { ColName = "pianchazhongliang", ValueMember = m_ChengZhongLeiXing == "入库物料" ? string.Format("{0}", m_CurrentRow["pianchazhongliang"]) : m_PianChaZhongLiang.ToString("0.00"), ValueType = DataValueCommonType.数字 });
                    newRow.DataCols.Add(new TableCol() { ColName = "chepaihao", ValueMember = txt_chepaihao.Text, ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "wuliaomingcheng", ValueMember = cmb_wuliao.Text, ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "xinghao", ValueMember = cmb_xinghao.Text, ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "danweimingcheng", ValueMember = cmb_danweimingcheng.Text, ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "quxiangbiaoduan", ValueMember = m_SheZhiQuXiang, ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "chengzhongleixing", ValueMember = m_ChengZhongLeiXing, ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "chengzhongbianhao", ValueMember = "", ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "jisuanfangliang", ValueMember = jiSuanFangLiang.ToString("0.00"), ValueType = DataValueCommonType.数字 });
                    newRow.DataCols.Add(new TableCol() { ColName = "maozhongshijian", ValueMember =m_ChengZhongLeiXing=="入库物料"?d1:d2, ValueType = DataValueCommonType.日期时间 });
                    newRow.DataCols.Add(new TableCol() { ColName = "pizhongshijian", ValueMember = m_ChengZhongLeiXing=="入库物料"?d2:d1, ValueType = DataValueCommonType.日期时间 });
                    newRow.DataCols.Add(new TableCol() { ColName = "maozhongrenyuan", ValueMember = m_ChengZhongLeiXing == "入库物料" ? string.Format("{0}", m_CurrentRow["chengzhongrenyuan"]) : string.Format("{0}", KeaoUtils._CurrentUserRow["yonghuxingming"]), ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "pizhongrenyuan", ValueMember = m_ChengZhongLeiXing == "入库物料" ? string.Format("{0}", KeaoUtils._CurrentUserRow["yonghuxingming"]) : string.Format("{0}", m_CurrentRow["chengzhongrenyuan"]), ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "maozhongtupian1", ValueMember =m_ChengZhongLeiXing=="入库物料"? m_CurrentRow["tupian1"]:tupian1, ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "maozhongtupian2", ValueMember = m_ChengZhongLeiXing=="入库物料"? m_CurrentRow["tupian2"]:tupian2, ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "maozhongtupian3", ValueMember =m_ChengZhongLeiXing=="入库物料"? m_CurrentRow["tupian3"]:tupian3, ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "pizhongtupian1", ValueMember = m_ChengZhongLeiXing == "入库物料" ? tupian1 : m_CurrentRow["tupian1"], ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "pizhongtupian2", ValueMember = m_ChengZhongLeiXing == "入库物料" ? tupian2 : m_CurrentRow["tupian2"], ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "pizhongtupian3", ValueMember = m_ChengZhongLeiXing == "入库物料" ? tupian3: m_CurrentRow["tupian3"], ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "jiage", ValueMember = "0.00", ValueType = DataValueCommonType.数字 });
                    newRow.DataCols.Add(new TableCol() { ColName = "jin_e", ValueMember = "0.00", ValueType = DataValueCommonType.数字 });
                    newRow.DataCols.Add(new TableCol() { ColName = "shangchuanzhuangtai", ValueMember = "0", ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "beizhu", ValueMember = "", ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "caozuojilu", ValueMember = "", ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName="yunshugongsi", ValueMember=cmb_yunshugongsi.SelectedIndex==0?"":cmb_yunshugongsi.Text, ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName="fahuozhongliang", ValueMember=string.Format("{0}",m_CurrentRow["fahuozhongliang"]), ValueType= DataValueCommonType.数字 });
                    newRow.DataCols.Add(new TableCol() { ColName = "zhandian", ValueMember = KeaoUtils.ConfigGetNodeAttr("客户", "站点"), ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "bangfang", ValueMember = KeaoUtils.ConfigGetNodeAttr("客户", "磅房"), ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "kehubianhao", ValueMember = KeaoUtils.ConfigGetNodeAttr("客户", "客户编号"), ValueType = DataValueCommonType.字符串 });
                    if (KeaoUtils._DB.SaveTableRows(newRow) > 0)
                    {
                        TableRow updateBianHaoRow = new TableRow() { TableName = "tbl_chengzhong", ID = newRow.ID, Ctl = DBCtl.修改 };
                        updateBianHaoRow.DataCols.Add(new TableCol() { ColName="chengzhongbianhao", ValueMember=KeaoUtils.GetSerialNumber(), ValueType= DataValueCommonType.字符串 });
                        KeaoUtils._DB.SaveTableRows(updateBianHaoRow);

                        KeaoUtils._DB.DeleteRowByID(new TableRow() { TableName = "tbl_chengzhonglinshi", ID = string.Format("{0}", m_CurrentRow["id"]) });//删除临时重量信息
                        //ThreadPool.QueueUserWorkItem(new WaitCallback(KeaoPrinter.Print), newRow.ID);
                        //Thread t = new Thread(new ParameterizedThreadStart(KeaoPrinter.Print));
                        //t.Start(newRow.ID);
                        KeaoPrinter.Print(newRow.ID, false);
                        if (m_ChengZhongLeiXing == "入库物料")
                        {
                            tabControl1.SelectedIndex = 2;
                        }
                        else
                        {
                            tabControl1.SelectedIndex = 3;
                        }

                        btn_refresh_Click(null, null);
                        if (tabControl1.SelectedIndex == 2)
                        {
                            lb_yici.Text = newRow.DataCols[0].ValueMember.ToString();
                            lb_erci.Text = newRow.DataCols[1].ValueMember.ToString();
                            lb_kouzhong.Text = newRow.DataCols[3].ValueMember.ToString();
                            lb_jingzhong.Text = newRow.DataCols[2].ValueMember.ToString();
                        }
                        else
                        {
                            lb_yici.Text = newRow.DataCols[1].ValueMember.ToString();
                            lb_erci.Text = newRow.DataCols[0].ValueMember.ToString();
                            lb_kouzhong.Text = newRow.DataCols[3].ValueMember.ToString();
                            lb_jingzhong.Text = newRow.DataCols[2].ValueMember.ToString();
                        }
                        if (OnChengZhong != null)
                        {
                            OnChengZhong(null, null);
                        }

                        DataTable ciShuDt = MainForm.m_CiShuDt as DataTable;
                        DataRow[] ciShuRows = ciShuDt.Select(string.Format("chepaihao='{0}' and chengzhongleixing='{1}'", newRow.DataCols[5].ValueMember,newRow.DataCols[10].ValueMember));
                        int ciShu = Convert.ToInt32(ciShuRows[0]["cishu"]);
                        int tmpCiShu = newRow.DataCols[10].ValueMember.Equals("入库物料")?int.Parse(KeaoUtils.ConfigGetNodeAttr("系统配置", "车辆运输次数预警")):int.Parse(KeaoUtils.ConfigGetNodeAttr("系统配置", "出库车辆运输次数预警"));
                        if (ciShu > tmpCiShu)
                        {
                            KeaoUtils.ShowInfoMessage("请注意，该车运输次数超出预设范围。");
                        }

                        try
                        {
                            if (m_CurrentCheLiangRow != null)
                            {
                                decimal cheLiangPiZhong = Convert.ToDecimal(m_CurrentCheLiangRow["cheliangpizhong"]);
                                if (cheLiangPiZhong > 0)
                                {
                                    //验证皮重差值
                                    if (m_PiZhong - cheLiangPiZhong > decimal.Parse(KeaoUtils.ConfigGetNodeAttr("系统配置", "皮重差")))
                                    {
                                        TableRow piZhongYiChaoChaRow = new TableRow("tbl_pizhongyichang", KeaoUtils.GetGUID(), DBCtl.插入);
                                        piZhongYiChaoChaRow.DataCols.Add(new TableCol() { ColName = "chepaihao", ValueMember = newRow.DataCols[5].ValueMember, ValueType = DataValueCommonType.字符串 });
                                        piZhongYiChaoChaRow.DataCols.Add(new TableCol() { ColName = "cheliangpizhong", ValueMember = cheLiangPiZhong.ToString("0.00"), ValueType = DataValueCommonType.数字 });
                                        piZhongYiChaoChaRow.DataCols.Add(new TableCol() { ColName = "chepichengzhong", ValueMember = m_PiZhong.ToString("0.00"), ValueType = DataValueCommonType.数字 });
                                        piZhongYiChaoChaRow.DataCols.Add(new TableCol() { ColName = "chaocha", ValueMember = (cheLiangPiZhong - m_PiZhong).ToString("0.00"), ValueType = DataValueCommonType.数字 });
                                        piZhongYiChaoChaRow.DataCols.Add(new TableCol() { ColName = "chengzhongbianhao", ValueMember = chengZhongID, ValueType = DataValueCommonType.字符串 });
                                        piZhongYiChaoChaRow.DataCols.Add(new TableCol() { ColName = "shangchuanzhuangtai", ValueMember = "0", ValueType = DataValueCommonType.字符串 });
                                        piZhongYiChaoChaRow.DataCols.Add(new TableCol() { ColName = "chengzhongshijian", ValueMember = d2, ValueType = DataValueCommonType.日期时间 });
                                        piZhongYiChaoChaRow.DataCols.Add(new TableCol() { ColName = "zhandian", ValueMember = KeaoUtils.ConfigGetNodeAttr("客户", "站点"), ValueType = DataValueCommonType.字符串 });
                                        piZhongYiChaoChaRow.DataCols.Add(new TableCol() { ColName = "kehubianhao", ValueMember = KeaoUtils.ConfigGetNodeAttr("客户", "客户编号"), ValueType = DataValueCommonType.字符串 });
                                        KeaoUtils._DB.SaveTableRows(piZhongYiChaoChaRow);
                                        if (OnChengZhongChaoCha != null)
                                        {
                                            OnChengZhongChaoCha(null, null);
                                        }

                                        KeaoUtils.ShowWarnMessage("该车皮重差值超出预警值！");
                                    }
                                }
                            }
                        }
                        catch (Exception err)
                        {
                            KeaoUtils.LogTxt(string.Format("验证皮重差异常。{0}", err.Message));
                        }
                        try
                        {
                            double tingLiuShiJian = (d2 - d1).TotalMinutes;
                            double tmpShiJian =  newRow.DataCols[10].ValueMember.Equals("入库物料") ? Convert.ToDouble(KeaoUtils.ConfigGetNodeAttr("系统配置", "称重超时")) : Convert.ToDouble(KeaoUtils.ConfigGetNodeAttr("系统配置", "出库称重超时"));
                            if (tingLiuShiJian > tmpShiJian)
                            {
                                //皮重超时
                                TableRow chaoShiRow = new TableRow("tbl_chaoshi", KeaoUtils.GetGUID(), DBCtl.插入);
                                chaoShiRow.DataCols.Add(new TableCol() { ColName = "chepaihao", ValueMember = newRow.DataCols[5].ValueMember, ValueType = DataValueCommonType.字符串 });
                                chaoShiRow.DataCols.Add(new TableCol() { ColName = "jinchangshijian", ValueMember = d1, ValueType = DataValueCommonType.日期时间 });
                                chaoShiRow.DataCols.Add(new TableCol() { ColName = "chuchangshijian", ValueMember = d2, ValueType = DataValueCommonType.日期时间 });
                                chaoShiRow.DataCols.Add(new TableCol() { ColName = "tingliushijian", ValueMember = tingLiuShiJian.ToString("0.00"), ValueType = DataValueCommonType.数字 });
                                chaoShiRow.DataCols.Add(new TableCol() { ColName = "chengzhongbianhao", ValueMember = chengZhongID, ValueType = DataValueCommonType.字符串 });
                                chaoShiRow.DataCols.Add(new TableCol() { ColName = "shangchuanzhuangtai", ValueMember = "0", ValueType = DataValueCommonType.字符串 });
                                chaoShiRow.DataCols.Add(new TableCol() { ColName = "zhandian", ValueMember = KeaoUtils.ConfigGetNodeAttr("客户", "站点"), ValueType = DataValueCommonType.字符串 });
                                chaoShiRow.DataCols.Add(new TableCol() { ColName = "kehubianhao", ValueMember = KeaoUtils.ConfigGetNodeAttr("客户", "客户编号"), ValueType = DataValueCommonType.字符串 });
                                KeaoUtils._DB.SaveTableRows(chaoShiRow);
                                if (OnChengZhongChaoShi != null)
                                {
                                    OnChengZhongChaoShi(null, null);
                                }

                                KeaoUtils.ShowWarnMessage("该车停留时长超出设定范围！");
                            }
                        }
                        catch (Exception err)
                        {
                            KeaoUtils.LogTxt(string.Format("验证皮重超时异常。{0}", err.Message));
                        }
                    }
                    else
                    {
                        KeaoUtils.ShowInfoMessage("保存数据失败，请重试。");
                        btn_refresh_Click(null, null);
                    }
                }
            }
            catch (Exception err)
            {
                KeaoUtils.LogTxt(string.Format("称重异常。{0}", err.Message));
            }
        }

        public event EventHandler OnChengZhong;
        public event EventHandler OnChengZhongChaoShi;
        public event EventHandler OnChengZhongChaoCha;

        #endregion

        #region 刷新数据

        private decimal m_BeiChuShu = Convert.ToDecimal(KeaoUtils.ConfigGetNodeAttr("称重设备", "被除数"));

        private void Tmr_UI_Tick(object sender, EventArgs e)
        {
            try
            {
                //界面数据刷新
                m_DangQianZhongLiang = m_YiBiaoDuShu / m_BeiChuShu;
                if (m_DangQianZhongLiang <= 0m)
                {
                    m_ListenSignl = false;//清空遥控监测信号
                }
                if (m_WeightStatus == WeightStatus.结束 && m_DangQianZhongLiang < 1m)
                {
                    m_PianChaZhongLiang = 0m;
                }
                if (m_ChengZhongLeiXing == "入库物料" && m_CurrentRow != null)
                {
                    m_PianChaZhongLiang = 0m;//重车进行偏差操作
                }
                if (m_ChengZhongLeiXing == "出库物料" && m_CurrentRow == null)
                {
                    m_PianChaZhongLiang = 0m;//重车进行偏差操作
                }

                if (m_DangQianZhongLiang <= 30m)
                {
                    m_PianChaHouZhongLiang = m_DangQianZhongLiang;
                }
                else
                {
                    m_PianChaHouZhongLiang = m_DangQianZhongLiang - m_PianChaZhongLiang;
                }

                u_weight1.SetNumber(m_PianChaHouZhongLiang.ToString("0.00"), m_WenDing);//设定偏差后重量，并显示到界面
                string sendStr = (m_PianChaHouZhongLiang * 1000m).ToString("0");

                if (m_Socket != null)
                {
                    m_Socket.Send(Encoding.Default.GetBytes(sendStr));
                }
            }
            catch (Exception err)
            {
                KeaoUtils.LogTxt(string.Format("刷新数据异常。{0}", err.Message));
            }
        }

        private void btn_refresh_Click(object sender, EventArgs e)
        {
            //m_BiaoDuan.ShowDialog();
            //刷新数据
            BindChuKuWeiWanCheng();
            BindRuKuWeiWanCheng();
            BindChuKuYiWanCheng();
            BindRuKuYiWanCheng();
            cmb_wuliao.SelectedIndex = 0;
            txt_chepaihao.Text = string.Empty;
            m_ZiDongChePiZhongLiang = 0m;
            pic_3.Image = null;
            pic_4.Image = null;
            m_CurrentRow = null;

            lb_yici.Text = "0.00";
            lb_erci.Text = "0.00";
            lb_kouzhong.Text = "0.00";
            lb_jingzhong.Text = "0.00";
            txt_kouzhong.Text = string.Empty;
            lb_kouzhongfangshi.Text = string.Empty;
            cmb_wuliao.DropDownStyle = ComboBoxStyle.DropDownList;
            cmb_xinghao.DropDownStyle = ComboBoxStyle.DropDownList;
            cmb_danweimingcheng.DropDownStyle = ComboBoxStyle.DropDownList;
            cmb_wuliao.Enabled = true;
            cmb_xinghao.Enabled = true;
            cmb_danweimingcheng.Enabled = true;
            txt_chepaihao.Enabled = true;
            txt_kouzhong.Enabled = false;
            cmb_yunshugongsi.Enabled = true;
            cmb_yunshugongsi.SelectedIndex = 0;

            if (sender != null)
            {
                BindWuLiao();
                m_PianChaZhongLiang = 0m;
            }
        }

        #endregion

        #region 车号改变，查询临时称重信息

        private void txt_chepaihao_TextChanged(object sender, EventArgs e)
        {
            //车号改变
            if (string.IsNullOrEmpty(txt_chepaihao.Text) || txt_chepaihao.Text == "—选择登记车辆—")
            {
                return;
            }
            string carNum = txt_chepaihao.Text;
            string createCondition = KeaoUtils._DB.CreateAndCondition("chepaihao", DataValueCommonType.字符串, carNum, "", SearchConditionType.等于);
            DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_chengzhonglinshi", createCondition);
            if (Dt.Rows.Count > 0)
            {
                cmb_yunshugongsi.Enabled = false;
                cmb_wuliao.Enabled = false;
                cmb_xinghao.Enabled = false;
                cmb_danweimingcheng.Enabled = false;
                txt_chepaihao.Enabled = false;
                txt_kouzhong.Enabled = true;

                m_CurrentRow = Dt.Rows[0];
                m_ChengZhongLeiXing  = string.Format("{0}", m_CurrentRow["chengzhongleixing"]);
                lb_yici.Text = string.Format("{0}", m_CurrentRow["yicizhongliang"]);
                lb_erci.Text = "0.00";
                lb_kouzhong.Text = "0.00";
                lb_jingzhong.Text = "0.00";
                cmb_wuliao.DropDownStyle = ComboBoxStyle.DropDown;
                cmb_xinghao.DropDownStyle = ComboBoxStyle.DropDown;
                cmb_danweimingcheng.DropDownStyle = ComboBoxStyle.DropDown;
                cmb_wuliao.Text = string.Format("{0}", m_CurrentRow["wuliaomingcheng"]);
                cmb_xinghao.Text = string.Format("{0}", m_CurrentRow["xinghao"]);
                cmb_danweimingcheng.Text = string.Format("{0}", m_CurrentRow["danweimingcheng"]);
                txt_kouzhong.Text = string.Format("{0}", m_CurrentRow["morenkouzhong"]);
                lb_kouzhongfangshi.Text = string.Format("{0}", m_CurrentRow["kouzhongfangshi"]);
                if (string.IsNullOrEmpty(lb_kouzhongfangshi.Text))
                {
                    lb_kouzhongfangshi.Text = "普通扣重";
                }
                cmb_yunshugongsi.Text = string.Format("{0}", m_CurrentRow["yunshugongsi"]);
                if (!m_CurrentRow["tupian1"].Equals("")&&m_Video!=null)
                {
                    string tupian1 = string.Format("{0}",m_CurrentRow["tupian1"]);
                    if (File.Exists(tupian1))
                    {
                        pic_3.Image = Image.FromFile(tupian1);
                    }
                }
                if (!m_CurrentRow["tupian2"].Equals("") && m_Video != null)
                {
                    string tupian2 = string.Format("{0}", m_CurrentRow["tupian2"]);
                    if (File.Exists(tupian2))
                    {
                        pic_4.Image = Image.FromFile(tupian2);
                    }
                }

                
            }
            else
            {
                m_CurrentRow = null;
                txt_kouzhong.Enabled = false;
            }

            string cheLiangCondition = KeaoUtils._DB.CreateAndCondition("chepaihao", DataValueCommonType.字符串, carNum, "", SearchConditionType.等于);
            cheLiangCondition += KeaoUtils._DB.CreateAndCondition("cheliangzhuangtai", DataValueCommonType.字符串, "启用", "", SearchConditionType.等于);
            DataTable cheLiangDt = KeaoUtils._DB.GetDataTableByCondition("tbl_cheliang", cheLiangCondition);
            if (cheLiangDt.Rows.Count > 0)
            {
                m_CurrentCheLiangRow = cheLiangDt.Rows[0];
                m_ZiDongChePiZhongLiang = 0m;
                if (cheLiangDt.Rows[0]["zidongchengzhong"].Equals("启用"))
                {
                    m_ZiDongChePiZhongLiang = Convert.ToDecimal(cheLiangDt.Rows[0]["cheliangpizhong"]);
                    txt_kouzhong.Enabled = true;
                    lb_yici.Text = m_ZiDongChePiZhongLiang.ToString();
                    if (string.IsNullOrEmpty(lb_kouzhongfangshi.Text))
                    {
                        lb_kouzhongfangshi.Text = "普通扣重";
                        txt_kouzhong.Text = "0";
                    }
                }
            }
            else
            {
                m_CurrentCheLiangRow = null;
                m_ZiDongChePiZhongLiang = 0m;
            }
        }
        #endregion

        #region 退出称重窗口

        private void ChengZhong_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (KeaoUtils.ShowQuestionMessage("是否退出称重系统界面？") == DialogResult.Yes)
            {
                if (m_Video != null)
                {
                    m_Video.CloseDevice();
                }
                if (CloseEvent != null)
                {
                    CloseEvent(null, null);   
                }
                if (m_Socket != null&&m_Socket.Connected)
                {
                    m_Socket.Shutdown(SocketShutdown.Both);
                    m_Socket.Close();
                }
                if (MainForm.m_Listener != null)
                {
                    MainForm.m_Listener.OnListenSignal -= m_Listener_OnListenSignal;
                }
            }
            else
            {
                e.Cancel = true;
                return;
            }
        }

        public event EventHandler CloseEvent;

        #endregion

        #region 运输公司

        private void BindYunShuGongSi()
        {
            string createCondition = KeaoUtils._DB.CreateAndCondition("gongsizhuangtai", DataValueCommonType.字符串, "启用", "", SearchConditionType.等于);
            DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_yunshugongsi", createCondition);
            DataRow newRow = Dt.NewRow();
            newRow["gongsimingcheng"] = "—请选择—";
            newRow["id"] = "";
            Dt.Rows.InsertAt(newRow, 0);
            cmb_yunshugongsi.DisplayMember = "gongsimingcheng";
            cmb_yunshugongsi.ValueMember = "id";
            cmb_yunshugongsi.DataSource = Dt;
        }

        #endregion


        private void txt_kouzhong_Click(object sender, EventArgs e)
        {
            txt_kouzhong.Focus();
            txt_kouzhong.SelectAll();
        }

        //称重退库
        private void contextMenu_2_tuiku_Click(object sender, EventArgs e)
        {
            if (!KeaoUtils._CurrentUserRow["juesequanxian"].ToString().Contains("退库操作"))
            {
                KeaoUtils.ShowInfoMessage("该用户没有权限进行此操作。");
                return;
            }

            if (tabControl1.SelectedIndex == 2)
            {
                if (!string.Format("{0}", KeaoUtils._CurrentUserRow["juesequanxian"]).Contains("入库物资退库"))
                {
                    KeaoUtils.ShowInfoMessage("该用户没有操作权限。");
                    return;
                }
                //入库退库
                if (grid_ruku_yiwancheng.SelectedRows.Count > 0)
                {
                    ChengZhongTuiKu chengZhongTuiKu = new ChengZhongTuiKu(grid_ruku_yiwancheng.SelectedRows[0],"入库物料");
                    chengZhongTuiKu.ShowDialog();
                }
            }
            if (tabControl1.SelectedIndex == 3)
            {
                if (!string.Format("{0}", KeaoUtils._CurrentUserRow["juesequanxian"]).Contains("出库物资退库"))
                {
                    KeaoUtils.ShowInfoMessage("该用户没有操作权限。");
                    return;
                }
                //出库退库
                if (grid_chuku_yiwancheng.SelectedRows.Count > 0)
                {
                    ChengZhongTuiKu chengZhongTuiKu = new ChengZhongTuiKu(grid_chuku_yiwancheng.SelectedRows[0],"出库物料");
                    chengZhongTuiKu.ShowDialog();
                }
            }
        }

       
        private void contextMenu_3_qiehuan_Click(object sender, EventArgs e)
        {
            tableLayoutPanel1.Visible = !tableLayoutPanel1.Visible;
        }

   

    }
}
